<template>
  <div class="dialog-container" style="margin-top: -30px;">
    <el-row>
      <!-- 线路站点table -->
      <el-col :span="10" style="padding-right: 5px;">
        <el-tabs v-model="activeTabName" class="demo-tabs" @tab-change="handleTabChange">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="success" plain icon="Plus" @click="handleEnter"
                v-hasPermi="['basic:routeStation:enter']">录入</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" @click="handleAdd"
                v-hasPermi="['basic:routeStation:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Edit" :disabled="!isEditStationOrder" @click="handleSaveStationOrder"
                v-hasPermi="['basic:routeStation:saveOrder']">保存站序</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                v-hasPermi="['basic:routeStation:remove']">删除</el-button>
            </el-col>
          </el-row>
          <el-tab-pane v-for="item in tabPanes" :key="item.name" :label="item.label" :name="item.name">
            <el-table v-loading="loading" :data="routeStationList" @selection-change="handleSelectionChange"
              @row-click="handleRowClick" max-height="500" highlight-current-row>
              <el-table-column type="selection" width="30" align="center" />
              <el-table-column label="站序" align="center" prop="stationOrder" width="70">
                <template #header>
                  <span style="display: flex;align-items: center;justify-content: center;"
                    @click="isEditStationOrder = !isEditStationOrder">站序
                    <el-icon>
                      <Edit />
                    </el-icon>
                  </span>
                </template>
                <template #default="scope">
                  <el-input input-style="text-align: center;--el-input-inner-height: 23px;"
                    v-model="scope.row.stationOrder" v-if="isEditStationOrder" />
                  <span v-else>{{ scope.row.stationOrder }}</span>
                </template>
              </el-table-column>
              <el-table-column label="站点" align="left" prop="stationName" />
              <el-table-column label="类型" align="center" prop="stationType" width="60">
                <template #default="scope">
                  <dict-tag :options="basic_route_station_type" :value="scope.row.stationType" />
                </template>
              </el-table-column>
              <el-table-column label="备注" align="left" prop="remark" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="210">
                <template #default="scope">
                  <el-button link type="primary" icon="Edit" @click="handleReplace(scope.row)"
                    v-hasPermi="['basic:routeStation:replace']">更换</el-button>
                  <el-button link type="success" icon="Edit" @click="handleUpdate(scope.row)"
                    v-hasPermi="['basic:routeStation:edit']">修改</el-button>
                  <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
                    v-hasPermi="['basic:routeStation:remove']">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-col>
      <!-- 线路轨迹地图 -->
      <el-col :span="14" style="padding-left: 5px;">
        <div id="routeLocusContainer"></div>
        <div id="locusOptionBox">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="warning" plain icon="View" @click="handleDraw">{{ locusOption.draw.text
              }}</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Edit" :disabled="locusSaveDisabled" @click="handleSaveLocus"
                v-hasPermi="['basic:routeLocus:save']">保存轨迹</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
              <el-button type="warning" plain icon="View" @click="handleShow">{{ locusOption.show.text
              }}</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain icon="Delete" @click="handleDelLocus"
                v-hasPermi="['basic:routeLocus:remove']">删除轨迹点</el-button>
            </el-col> -->
          </el-row>
        </div>
      </el-col>
    </el-row>

    <!-- 录入或修改线路站点对话框 -->
    <el-dialog :title="title" v-model="open" :width="form.id == null ? '60%' : '600px'" append-to-body>
      <el-form ref="routeStationRef" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <!-- 线路站点表单 -->
          <el-col :span="form.id == null ? 10 : 24" :style="form.id == null ? 'padding-right: 5px;' : ''">
            <el-row>
              <el-col v-if="form.id == null">
                <el-form-item label="地区" prop="areaId">
                  <el-cascader v-model="form.areaId" :options="areaOptions"
                    :props="{ value: 'id', label: 'label', children: 'children', emitPath: false }" placeholder="请选择地区"
                    filterable :show-all-levels="false" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="站点名称" prop="stationName">
                  <el-input v-model="form.stationName" placeholder="请输入站点名称" @focus="handleFocusOpen" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" placeholder="请输入备注" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="站点类型" prop="stationType">
                  <el-select filterable v-model="form.stationType" placeholder="请选择站点类型">
                    <el-option v-for="dict in basic_route_station_type" :key="dict.value" :label="dict.label"
                      :value="parseInt(dict.value)"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态" prop="status">
                  <el-select filterable v-model="form.status" placeholder="请选择状态">
                    <el-option v-for="dict in sys_data_status" :key="dict.value" :label="dict.label"
                      :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="经度" prop="longitude">
                  <el-input v-model="form.longitude" placeholder="请输入经度" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="纬度" prop="latitude">
                  <el-input v-model="form.latitude" placeholder="请输入纬度" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="距首站距离" prop="firstStationDistance">
                  <el-input v-model="form.firstStationDistance" placeholder="请输入距首站距离(米)" />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="form.id == null">
                <el-form-item label="方位角" prop="directionAngle">
                  <el-input v-model="form.directionAngle" placeholder="请输入方位角" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row style="justify-content: right;">
              <div style="padding-top: 30px;">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
              </div>
            </el-row>
          </el-col>
          <!-- 录入线路站点时用到的poi搜索地图 -->
          <el-col :span="14" style="padding-left: 5px;" v-if="form.id == null">
            <mapPoi :containerId="'routeStaionEnterContainer'" ref="mapPoiRef" @emitLngLat="listenLngLat" />
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <!-- 新增或更换线路站点对话框 -->
    <el-dialog :title="titleTable" v-model="openTable" width="50%" append-to-body :before-close="cancelTable">
      <stationTable ref="chooseStationRef" :queryParams="stationSearchParams" @emitStationData="listenStationChoose">
        <template #button>
          <div style="padding: 0 0 15px 0;">
            <el-button :loading="buttonLoading" type="primary" @click="submitChoose">确 定</el-button>
            <el-button @click="cancelTable">取 消</el-button>
          </div>
        </template>
      </stationTable>
    </el-dialog>
  </div>
</template>

<script setup name="RouteStation">
import { listRouteStation, getRouteStation, delRouteStation, addRouteStation, updateRouteStation, enterRouteStation, replaceRouteStation, batchUpdateRouteStationOrder } from "@/api/basic/routeStation";
import { listRouteLocusAll, addRouteLocus, updateRouteLocus, delRouteLocus } from "@/api/basic/routeLocus";
import { areaTreeSelect } from "@/api/basic/area";
import mapPoi from "@/views/basic/station/components/mapPoi";
import stationTable from './components/stationTable'

const { proxy } = getCurrentInstance();
const { sys_data_status, basic_route_station_type } = proxy.useDict('sys_data_status', 'basic_route_station_type');

const props = defineProps({
  routeId: [Number, String]
})
const routeStationList = ref([]);
const routeLocusList = ref([]);
const routeViasList = ref([]);
const isEditStationOrder = ref(false);
const open = ref(false);
const buttonLoading = ref(false);
const openTable = ref(false);
const buttonTableLoading = ref(false);
const loading = ref(true);
const deleteRow = ref([]);
const single = ref(true);
const multiple = ref(true);
const locusSaveDisabled = ref(true)
const title = ref("");
const titleTable = ref("");
const isFocusEditOpen = ref(false)
const areaOptions = ref([])
const activeTabName = ref(1)
const tabPanes = [{
  label: '上行站点',
  name: 1,
}, {
  label: '下行站点',
  name: 2,
}]

const data = reactive({
  form: {},
  tempForm: {}, //选择站点列表后返回的临时变量
  queryParams: {
    routeId: undefined,
    direction: 1,
  },
  stationSearchParams: {},
  routeData: {
    id: undefined,
    locus: undefined,
    vias: undefined
  },
  rules: {
    areaId: [
      { required: true, message: "地区不能为空", trigger: "change" }
    ],
    stationName: [
      { required: true, message: "站点名称不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ],
    stationOrder: [
      { required: true, message: "站序不能为空", trigger: "blur" }
    ],
    stationType: [
      { required: true, message: "站点类型不能为空", trigger: "change" }
    ],
    longitude: [
      { required: true, message: "经度不能为空", trigger: "blur" }
    ],
    latitude: [
      { required: true, message: "纬度不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules, stationSearchParams, routeData } = toRefs(data);

/** 查询地区下拉树结构 */
function getAreaTree() {
  areaTreeSelect().then(response => {
    areaOptions.value = response.data;
  })
}

/** 查询线路站点列表 */
function getList() {
  return new Promise((resolve, reject) => {
    loading.value = true;
    listRouteStation(queryParams.value).then(response => {
      routeStationList.value = response.data;
      loading.value = false;
      locusOption.value.draw.isOpen = false;

      resolve('线路站点获取完成')
      console.log('线路站点获取完成')
    });
  })
}

/** 查询线路所有轨迹和途经点
 *  fix:此处用promise 是因为在保存轨迹后要重新调用改方法，且重新加载地图轨迹
 */
function getLocus() {
  return new Promise((resolve, reject) => {
    listRouteLocusAll(queryParams.value).then(response => {
      let locus = [];
      let vias = [];

      if (response.data != null) {
        routeData.value.id = response.data.id
        if (response.data.locus) {
          let tempLocus = response.data.locus.split(';')
          tempLocus.forEach(item => {
            let t = item.split(',')
            locus.push([t[0], t[1]])
          })
        }
        if (response.data.vias) {
          let tempVias = response.data.vias.split(';')
          tempVias.forEach(item => {
            let t = item.split(',')
            vias.push([t[0], t[1]])
          })
        }
      } else {
        routeData.value.id = null
      }
      routeLocusList.value = locus
      routeViasList.value = vias

      resolve('线路轨迹获取完成')
      console.log('线路轨迹获取完成')
    })
  })
}

// 取消表单按钮
function cancel() {
  open.value = false;
  reset();
}

//取消站点选择列表按钮
function cancelTable() {
  isFocusEditOpen.value = false;
  openTable.value = false;
  data.tempForm = {};
}


// 表单重置
function reset() {
  form.value = {
    id: null,
    routeId: props.routeId,
    stationId: null,
    areaId: null,
    stationName: null,
    remark: null,
    stationType: 3,
    longitude: null,
    latitude: null,
    firstStationDistance: null,
    directionAngle: null,
    status: '0',
    direction: queryParams.value.direction
  };
  proxy.resetForm("routeStationRef");
}

// 多选框选中数据
function handleSelectionChange(selection) {
  deleteRow.value = selection.map(item => item); //用于删除，需要传整个数据
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 保存站序按钮操作 */
function handleSaveStationOrder() {
  if (isEditStationOrder.value == false) {
    proxy.$modal.msgError('请先编辑站序');
    return;
  }
  let _data = [];
  routeStationList.value.forEach(item => {
    _data.push(item)
  })
  let size = new Set(_data.map(item => item.stationOrder)).size
  if (size != _data.length) {
    proxy.$modal.msgError('站序不能出现重复');
    return;
  }
  batchUpdateRouteStationOrder(_data).then(response => {
    proxy.$modal.msgSuccess("保存成功");
    isEditStationOrder.value = false;
    locusRouteInit();
    
    resetSiteLocus(true, false, true, false);
  })
}

/** 录入按钮操作 */
function handleEnter() {
  reset();
  open.value = true;
  title.value = "录入站点并添加线路站点";

  nextTick(() => {
    proxy.$refs["mapPoiRef"].newMap();
  })
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  openTable.value = true;
  titleTable.value = "添加线路站点";
  stationSearchParams.value = {
    name: "",
  }
}

/** 更换按钮操作 */
function handleReplace(row) {
  loading.value = true
  reset();
  const _id = row.id
  getRouteStation(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    openTable.value = true;
    titleTable.value = "更换线路站点";
    // 传递查询值给站点搜索列表
    stationSearchParams.value = {
      name: form.value.stationName,
    }
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id
  getRouteStation(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改线路站点";
  });
}

/** 修改表单内站点名称获取焦点时触发操作 */
function handleFocusOpen() {
  if (form.value.id == null) {
    return
  }
  isFocusEditOpen.value = true;
  openTable.value = true;
  titleTable.value = '选择站点'
  stationSearchParams.value = {
    name: "",
  }
}

/** 录入或修改的提交按钮 */
function submitForm() {
  proxy.$refs["routeStationRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateRouteStation(form.value).then(async (response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          isFocusEditOpen.value = false;
          data.tempForm = {};
          locusRouteInit();

          resetSiteLocus(true, false, true, true);
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        enterRouteStation(form.value).then(async (response) => {
          proxy.$modal.msgSuccess("录入成功");
          open.value = false;
          locusRouteInit();

          resetSiteLocus(true, false, true, true);
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

// 监听站点选择
function listenStationChoose(e) {
  data.tempForm = e;
}

/** 新增或更换的提交按钮 */
function submitChoose() {
  buttonTableLoading.value = true
  if (Object.keys(data.tempForm).length == 0) {
    proxy.$modal.msgError('请选择站点');
    buttonTableLoading.value = false;
    return;
  }

  // 赋值给form
  form.value.stationId = data.tempForm.id;
  form.value.areaId = data.tempForm.areaId;
  form.value.stationName = data.tempForm.name;
  form.value.remark = data.tempForm.remark;
  form.value.longitude = data.tempForm.longitude;
  form.value.latitude = data.tempForm.latitude;
  form.value.directionAngle = data.tempForm.directionAngle;

  //判断是否是通过编辑弹框打开了站点查询table,是的话 就只赋值给表单form参数
  if (isFocusEditOpen.value) {
    openTable.value = false;
    buttonTableLoading.value = false;
    return;
  }

  //清空选择站点列表后返回的临时变量
  data.tempForm = {}

  if (form.value.id != null) {
    replaceRouteStation(form.value).then(async (response) => {
      proxy.$modal.msgSuccess('更换成功');
      openTable.value = false;
      locusRouteInit();

      resetSiteLocus(true, false, true, true);
    }).finally(() => {
      buttonTableLoading.value = false;
    })

  } else {
    addRouteStation(form.value).then(async (response) => {
      proxy.$modal.msgSuccess('新增成功');
      openTable.value = false;
      locusRouteInit();

      resetSiteLocus(true, false, true, true);
    }).finally(() => {
      buttonTableLoading.value = false;
    })
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  let _data = [];
  let _orders = [];
  if (typeof row.id != 'undefined') {
    _data.push(row);
    _orders.push(row.stationOrder)
  } else {
    deleteRow.value.forEach(item => {
      _data.push(item)
      _orders.push(item.stationOrder)
    })
  }
  _orders = _orders.join(',');
  proxy.$modal.confirm('是否确认删除线路站点站序为"' + _orders + '"的数据项？').then(function () {
    loading.value = true;
    return delRouteStation(_data);
  }).then(async (response) => {
    proxy.$modal.msgSuccess("删除成功");
    loading.value = true;
    locusRouteInit();

    resetSiteLocus(true, false, true, true);
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

getAreaTree();

/** 监听地图poi后赋值表单经纬度 */
function listenLngLat(e) {
  form.value.longitude = e.longitude
  form.value.latitude = e.latitude
}


/**************************  分隔线  *****************************/


import { initMap } from '@/utils/map';
import startPg from '@/assets/images/site_s.png';
import endPg from '@/assets/images/site_e.png';
import tjPg from '@/assets/images/site_t.png';
/** 申明map对象 */
const Map = shallowReactive({
  myMap: {},
  map: null,
  labelsLayer: null,
  polyline: null,
  dragRoute: null
})

async function newMap() {
  Map.myMap = await initMap();

  if (Map.map == null) {
    Map.map = new Map.myMap.Map('routeLocusContainer', {
      zoom: 11
    })
  } else {
    Map.map.clearMap()
  }

  resetSiteLocus();
}

const sitePng = reactive({
  s: startPg,
  e: endPg,
  t: tjPg
})

// 加载地图站点
function loadMapSite() {
  console.log('加载地图站点')
  Map.labelsLayer != null && Map.map.remove(Map.labelsLayer)

  Map.labelsLayer = new Map.myMap.LabelsLayer({
    zIndex: 119,
    collision: false, // 文字避让
    animation: true
  })

  let length = routeStationList.value.length;
  if (length < 2) {
    return
  }
  // console.log(routeStationList.value)
  routeStationList.value.forEach((item, i) => {
    let png = sitePng.t
    if (i == 0) {
      png = sitePng.s;
    }
    if (i == length - 1) {
      png = sitePng.e;
    }
    let info = {
      position: [item.longitude, item.latitude],
      zIndex: 120 + i,
      rank: 1000,
      icon: {
        type: 'image',
        image: png,
        size: [16, 24],
        anchor: 'bottom-center',
        angel: 0,
        retina: true
      },
      text: {
        content: item.stationOrder + '_' + item.stationName,
        direction: 'center',
        offset: [0, -25],
        style: {
          fontSize: 11,
          fontWeight: 'bold',
          fillColor: '#000',
          strokeColor: '#fff',
          strokeWidth: 1,
        }
      }
    }
    Map.labelsLayer.add(new Map.myMap.LabelMarker(info))
  })
  Map.map.add(Map.labelsLayer)
}

// 加载地图轨迹
function loadMapLocus() {
  console.log('加载地图轨迹')
  Map.polyline != null && Map.map.remove(Map.polyline)

  Map.polyline = new Map.myMap.Polyline({
    map: Map.map,
    showDir: true,
    strokeColor: "#3366FF",     //线颜色
    strokeOpacity: 0.9,         //线透明度
    lineJoin: "round",           //线拐点的绘制样式
    lineCap: "round",           //线两端线帽的绘制样式
    strokeWeight: 4,            //线宽
    strokeStyle: "solid",       //线样式
  })

  let path = [];
  if (routeLocusList.value.length < 2) {
    //使用首末站点作为轨迹
    let siteLength = routeStationList.value.length
    if (siteLength < 2) {
      proxy.$modal.msgError('至少添加2个站点才能进行轨迹初始化');
      return;
    }
    routeStationList.value.forEach((item, i) => {
      if (i == 0 || (i == siteLength - 1)) {
        path.push([item.longitude, item.latitude])
      }
    })
  } else {
    routeLocusList.value.forEach(item => {
      path.push(item)
    })
  }

  Map.polyline.setPath(path)
  Map.map.setFitView([Map.polyline], false, [60, 60, 60, 60], Map.map.getZoom())
}

// 加载可拖拽路线
function loadDragRoute() {
  let siteLength = routeStationList.value.length
  if (routeViasList.value.length == 0 && siteLength < 2) {
    proxy.$modal.msgError('缺失构成拖拽导航的途径点')
    resetLocusOption()
    return;
  }

  //使用轨迹的首末点和轨迹的途经点 或站点首末站点 组合成拖拽导航需要用到的途经点参数
  let locusLength = routeLocusList.value.length
  let vias = [];
  vias[0] = locusLength >= 2 ? routeLocusList.value[0] : [routeStationList.value[0].longitude, routeStationList.value[0].latitude]
  routeViasList.value.forEach(item => {
    vias.push(item)
  })
  vias[vias.length] = locusLength >= 2 ? routeLocusList.value[locusLength - 1] : [routeStationList.value[siteLength - 1].longitude, routeStationList.value[siteLength - 1].latitude]

  Map.dragRoute = new Map.myMap.DragRoute(Map.map, vias, Map.myMap.DrivingPolicy.LEAST_DISTANCE, {
    polyOption: {
      lineJoin: "round",         //线拐点的绘制样式
      lineCap: "square",         //线两端线帽的绘制样式
      strokeColor: "#ce0000",    //线颜色
      strokeWeight: 4,           //线宽
      strokeStyle: "solid",      //线样式
      strokeOpacity: 0.9,        //线条透明度
      showDir: true,             //是否延路径显示白色方向箭头
      isOutline: false,          //线条是否带描边
    }
  })
  Map.dragRoute.search()

  Map.dragRoute.on('complete', function (data) {
    if (Map.dragRoute.getWays().length > 10) {
      proxy.$modal.msgError('拖拽导航规划的途经点不能超过10个');
      return
    }
    // 所有轨迹点
    let tempLocus = '';
    Map.dragRoute.getRoute().forEach(item => {
      tempLocus += item.toString() + ';'
    })
    routeData.value.locus = tempLocus.replace(/;$/gi, '')
    //拖拽产生的途经点
    let tempVias = ''
    Map.dragRoute.getWays().forEach(item => {
      tempVias += item.toString() + ";"
    })
    routeData.value.vias = tempVias.replace(/;$/gi, '')
  })
}

const locusOption = ref({
  draw: {
    icon: 'TurnOff',
    text: '绘制轨迹',
    isOpen: false,
  },
  show: {
    icon: 'TurnOff',
    text: '展示轨迹点',
    isOpen: false,
  }
})

//重置线路轨迹操作的相关数值
function resetLocusOption() {
  locusSaveDisabled.value = true;
  locusOption.value.draw.text = '绘制轨迹';
  locusOption.value.draw.isOpen = false;
}

//重置保存轨迹需要的相关数值
function resetRouteData() {
  routeData.value.locus = null
  routeData.value.vias = null
}

//销毁可拖拽路线
function destroyDragRoute(){
  Map.dragRoute != null && Map.dragRoute.destroy()
}

//当执行录入、新增、更换、修改线路站点后初始化可能会引起的绘制轨迹后 但未保存轨迹的相关数据
function locusRouteInit(){
  resetLocusOption();
  resetRouteData();
  destroyDragRoute();
}

// 绘制轨迹按钮操作
function handleDraw() {
  if (locusOption.value.draw.isOpen != true) {
    locusSaveDisabled.value = false;
    locusOption.value.draw.text = '取消绘制';
    locusOption.value.draw.isOpen = true;
    loadDragRoute();
  } else {
    locusRouteInit();
    Map.polyline != null && Map.map.setFitView([Map.polyline], false, [60, 60, 60, 60], Map.map.getZoom())
  }
}

//保存轨迹
function handleSaveLocus() {
  let data = {
    routeId: queryParams.value.routeId,
    direction: queryParams.value.direction,
    id: routeData.value.id,
    locus: routeData.value.locus,
    vias: routeData.value.vias,
    status: 0
  }

  let requestUrl;
  let tips;
  if (routeLocusList.value.length) {
    //修改线路轨迹
    requestUrl = updateRouteLocus;
    tips = '修改'
  } else {
    //新增线路轨迹
    requestUrl = addRouteLocus;
    tips = '新增'
  }
  requestUrl(data).then(async (response) => {
    proxy.$modal.msgSuccess(tips + '成功');
    isEditStationOrder.value = false;
    locusRouteInit();

    resetSiteLocus(false, true, false, true)
  });
}

//轨迹点开启或关闭操作
/*function handleShow() {
  if (locusOption.value.show.isOpen != true) {
    locusOption.value.show.text = '关闭轨迹点';
  } else {
    locusOption.value.show.text = '展示轨迹点';
  }
  locusOption.value.show.isOpen = !locusOption.value.show.isOpen
}*/

// 表格某一行的单击事件
function handleRowClick(row, column) {
  if (Map.map == null || column.property == "stationOrder") {
    return;
  }
  Map.map.setCenter([row.longitude, row.latitude])
  Map.map.setZoom(16)
}

// 监听tab切换栏
const handleTabChange = (tabName) => {
  queryParams.value.direction = tabName
  activeTabName.value = tabName
  resetMethodAttr();
}

/** 监听线路ID属性变化 */
watch(props, (newVal, oldVal) => {
  // console.log(newVal, oldVal)
  queryParams.value.routeId = newVal.routeId
  queryParams.value.direction = 1
  activeTabName.value = 1
  resetMethodAttr();
}, { immediate: true })

// 监听tab切换栏时和线路ID属性变化时 重新调用和初始一些方法和数值
function resetMethodAttr() {
  isEditStationOrder.value = false;

  locusRouteInit();

  newMap();
}
// 重置调用地区用到的获取数据和加载地图相关对象的方法
async function resetSiteLocus(getSite = true, getPath = true, loadSite = true, loadPath = true) {
  getSite && await getList();
  getPath && await getLocus();

  loadSite && loadMapSite();
  loadPath && loadMapLocus();
}
</script>
<style scoped>
#routeLocusContainer {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 600px;
}

#locusOptionBox {
  position: absolute;
  z-index: 9999;
  top: 10px;
  right: 10px;
}
</style>
